'use strict';
var jwt = require('jsonwebtoken');

module.exports = app => {
  return class extends app.Controller {
    * login(ctx) {
        var wechatId=ctx.request.header.wechatid;
        var code=ctx.request.query.code;
        var wp=yield ctx.model.Wechat.findById(wechatId);
        wp.accessToken=wp.accessToken ? JSON.parse(wp.accessToken) : null;

        var url='https://api.weixin.qq.com/sns/jscode2session?appid='+wp.appId+'&secret='+wp.appSecret+'&js_code='+code+'&grant_type=authorization_code';
        const result =yield ctx.curl(url,{dataType: 'json'});
        console.log(result);
        var user=yield ctx.model.User.findOne({where:{openid:result.data.openid}});
        if(user){
            user.sessionKey=result.data.session_key;
            user.expiresIn=new Date()+result.data.expires_in;
            user.save();
        }else {
            user=yield ctx.model.User.create({sessionKey:result.data.session_key,openid:result.data.openid,wechatId:wechatId});
        }
        console.log(user);
        var token=jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60),
            data: {
                user:{
                    id:user.id
                }
            }
        }, ctx.locals.tokenScrect);
        console.log(token);


        ctx.body={token:token};
    }
  };
};
